﻿using Microsoft.Extensions.Caching.Memory;
using System;

namespace CommonDevelop.Cache
{
    /// <summary>
    /// 简单系统缓存池(支持附件上传)
    /// </summary>
    public class SystemCache
    {
        private static MemoryCache Cache = new MemoryCache(new MemoryCacheOptions());
        /// <summary>
        /// 获取缓存值
        /// </summary>
        public static object GetCacheValue(string key)
        {
            object val = null;
            if (key != null && Cache.TryGetValue(key, out val))
                return val;
            else
                return default(object);
        }

        /// <summary>
        /// 添加缓存内容
        /// </summary>
        public static void SetChacheValue(string key, object value)
        {
            if (!string.IsNullOrWhiteSpace(key))
            {
                Cache.Set(key, value, new MemoryCacheEntryOptions
                {
                    SlidingExpiration = TimeSpan.FromHours(2)
                });
            }
        }
        public static void SetChacheValue(string key, object value, DateTime expire)
        {
            if (!string.IsNullOrWhiteSpace(key))
            {
                Cache.Set(key, value, new MemoryCacheEntryOptions
                {
                    SlidingExpiration = expire - DateTime.Now
                });
            }
        }

        public static void Write<T>(string key, T value)
        {
            if (!string.IsNullOrWhiteSpace(key))
                Cache.Set<T>(key, value);
        }

        public static void Write<T>(string key, T value, DateTimeOffset absoluteExpiration)
        {
            if (!string.IsNullOrWhiteSpace(key))
                Cache.Set<T>(key, value, absoluteExpiration);
        }

        public static T Read<T>(string key)
        {
            if (!string.IsNullOrWhiteSpace(key))
                return Cache.Get<T>(key);
            else
                return default(T);
        }

        public static bool RemoveCache(string key)
        {
            if (string.IsNullOrEmpty(key))
                return false;

            Cache.Remove(key);
            return true;
        }
    }
}
